<?php

namespace app\pay\model;

use think\Model;
use think\Db;

class Plan extends Model
{
	/**
	 * 代偿回调方法
	 *
	 * @param        $res              【上游通道返回的支付结果】
	 * @param array  $plan 【当前代付的计划】
	 * @param string $type 【1同步返回处理2异步返回处理】
	 *
	 * @return array            【返回结果】
	 */
	public function payNotify($res, $type = "1")
	{
		$plan_form_no = $res["dsorderid"];
		$msg = isset($res["errtext"]) ? $res["errtext"] : "";
		if ($type == 1) {//这是同步接口方法
			if ($res["returncode"] == "0000") {//支付成功
				return $this->doPayNotify($plan_form_no, $msg, 1);
			} elseif ($res["returncode"] == "0001") {//支付失败
				return $this->doPayNotify($plan_form_no, $msg, 2);
			} elseif ($res["returncode"] == "0003") {//支付处理中
				return $this->doPayNotify($plan_form_no, $msg, 3);
			} else {
				Db::name("plan")->where(["plan_form_no" => $plan_form_no])->update(["plan_time" => date("Y-m-d H:i:s"), "plan_msg" => $msg]);
				return ["error" => "2", "msg" => $msg, "mission_id"=>''];
			}
		} elseif ($type == 2) {//这是异步接口方法
			if ($res["status"] == "00") {//支付成功
				return $this->doPayNotify($plan_form_no, $msg, 1);
			} elseif ($res["status"] == "02") {//支付失败
				return $this->doPayNotify($plan_form_no, $msg, 2);
			} elseif ($res["status"] == "01") {//支付处理中
				return $this->doPayNotify($plan_form_no, $msg, 3);
			} else {
				Db::name("plan")->where(["plan_form_no" => $plan_form_no])->update(["plan_time" => date("Y-m-d H:i:s"), "plan_msg" => $msg]);
				return ["error" => "2", "msg" => $msg, "mission_id"=>''];
			}
		}
	}


	/**
	 * 处理代付回调业务逻辑
	 *
	 * @param $plan         【当前执行的计划】
	 * @param $plan_msg     【支付返回的信息】
	 * @param $type         【支付状态；1成功2支付失败2支付处理中】
	 *
	 * @return array
	 */
	public function doPayNotify($plan_form_no, $plan_msg, $type)
	{
		$plan = Db::name("plan")->where(["plan_form_no"=>$plan_form_no])->find();
		if ($plan["plan_state"] == 1) {
			return ["error" => 1, "msg" => $plan_msg, "mission_id"=>''];
		}
		$mission = Db::name('mission')->where('mission_id', $plan['plan_mid'])->find();
		if ($type == 1) {
			if ($plan['plan_type'] == '1') {//还款
				//更新plan为已支付
				Db::name('plan')->where(['plan_id' => $plan['plan_id']])->update(['plan_state' => 1, 'plan_msg' => $plan_msg, 'plan_time' => date('Y-m-d H:i:s')]);
				//增加还款笔数
				Db::name('mission')->where(['mission_id' => $plan['plan_mid']])->setInc('mission_repayment_number');

				//还款以后判断当前计划是否结束
				if (($mission["mission_repayment_number"] + 1) == $mission["mission_repayment"]) {//如果已还款笔数==还款笔数说明计划ok
					//计划完成
					Db::name('mission')->where(['mission_id' => $plan['plan_mid']])->update(['mission_type' => 0, 'mission_current_state' => 3, 'mission_state' => 2, 'mission_queues' => 0]);
					//更改信用卡状态
					Db::name('user_card')->where(['card_id' => $mission['mission_cid']])->update(['card_state' => 0]);
				} elseif ($mission["mission_repayment_number"] < $mission["mission_repayment"]) {//如果还有计划未完成切换计划当前状态为消费状态
					//获取下一次执行计划的时间
					$payTime = Db::name('plan')->where(['plan_state' => 0, 'plan_type' => 2, 'plan_mid' => $plan['plan_mid']])->order('plan_pay_time asc')->value('plan_pay_time');
					//更新队列为出队，同时状态改为消费状态，并更新下次支付的时间
					Db::name('mission')->where(['mission_id' => $plan['plan_mid']])->update(['mission_type' => 0, 'mission_current_state' => 2, 'mission_pay_time' => $payTime, 'mission_queues' => 0]);
				}
				//接下来是判断用户以外终止计划没有如果终止了就更新状态
				switch ($mission['mission_close']) {
					case '2':
						//用户提交关闭计划
						Db::name('mission')->where('mission_id', $plan['plan_mid'])->update(['mission_state' => 4]);
						Db::name('user_card')->where('card_id', $mission['mission_cid'])->update(['card_state' => 0]);
						break;
					case '3':
						//用户提交删除
						Db::name('mission')->where('mission_id', $plan['plan_mid'])->update(['mission_del' => 1, 'mission_state' => 3]);
						Db::name('user_card')->where('card_id', $mission['mission_cid'])->update(['card_state' => 0]);
						break;
					default:
						Db::name('mission')->where('mission_id', $plan['plan_mid'])->update(['mission_close' => 1]);
						break;
				}
				//增加用户还款金额
				Db::name('user')->where(['user_id' => $plan['plan_uid']])->setInc('user_repay_amount', $plan['plan_money']);

			} elseif ($plan['plan_type'] == '2') {//消费
				//更新订单为已支付
				Db::name('plan')->where('plan_id', $plan['plan_id'])->update(['plan_state' => 1, 'plan_msg' => $plan_msg, 'plan_time' => date('Y-m-d H:i:s')]);
				//增加扣款笔数
				Db::name('mission')->where(['mission_id' => $plan['plan_mid']])->setInc('mission_consume_number');
				//增加当前计划的已扣费率
				Db::name('mission')->where(['mission_id' => $plan['plan_mid']])->setInc('mission_at_fee', $plan["plan_fee"]);

				$payTime = Db::name('plan')->fetchSql(0)->where(['plan_state' => 0, 'plan_type' => 2, 'plan_mid' => $plan['plan_mid'], 'plan_sort' => $plan['plan_sort']])->order('plan_pay_time asc')->value('plan_pay_time');
				//halt($payTime);
				if ($payTime) {//如果还有未消费的账单，更改计划状态为消费状态
					$mission_current_state = 2;
				} else {//如果刷的是第三笔，那么更改计划状态为还款
					$payTime = Db::name('plan')->where(['plan_state' => 0, 'plan_type' => 1, 'plan_mid' => $plan['plan_mid'], 'plan_sort' => $plan['plan_sort']])->order('plan_pay_time asc')->value('plan_pay_time');
					$mission_current_state = 1;
				}
				$data['mission_current_state'] = $mission_current_state;
				$data['mission_pay_time'] = $payTime;
				$data['mission_queues'] = 0;
				$data['mission_type'] = 0;
				//计划执行到半道的时候是不允许用户终止计划的
				$data['mission_close'] = 0;
				Db::name('mission')->where(['mission_id' => $plan['plan_mid']])->update($data);
				//分润
				controller('pay/Profit')->repayment($plan_form_no);
			}
		} elseif ($type == 2) {//执行失败处理方法
			Db::name('plan')->where('plan_id', $plan['plan_id'])->update(['plan_state' => 2, 'plan_msg' => $plan_msg, 'plan_time' => date('Y-m-d H:i:s')]);
			Db::name('mission')->where('mission_id', $plan['plan_mid'])->update(['mission_type' => 2, 'mission_state'=>3]);
			//$this->autohuan($mission,$plan);
			return ["error" => 2, "msg" => $plan_msg, "mission_id"=>''];
		} elseif ($type == 3) {//账单处理中
			Db::name('plan')->where('plan_id', $plan['plan_id'])->update(['plan_state' => 3, 'plan_msg' => $plan_msg, 'plan_time' => date('Y-m-d H:i:s')]);
			//更改队列为处理中,并且用户禁止终止计划
			Db::name("mission")->where(["mission_id"=>$plan["plan_mid"]])->update(["mission_type"=>3,'mission_state'=>1,"mission_close"=>0,'mission_queues'=>1]);
			return ["error" => 3, "msg" => $plan_msg, "mission_id"=>''];
		}
		return ["error" => 0, "msg" => $plan_msg, "mission_id"=>$mission["mission_id"]];
	}


	//执行失败以后自动还款
	public function autohuan($mission,$plan){
		//$mission=Db::name("mission")->find(2);
		//$plan=Db::name("plan")->find(5);
		$data=[];
		$data["uid"]=$mission["mission_uid"];
		$data["mission_id"]=$mission["mission_id"];
		$data["fail_form_no"]=$plan["plan_form_no"];
		$data["plan_form_no"]=get_order_sn("C", $data["uid"]);
		$data["fail_money"]=0;
		$data["fail_fee"]=0;
		$data["pay_id"]=$mission["mission_pay_id"];
		$data["payment_controller"] = $payment_controller = Db::name("payment")->where(["payment_id"=>$data["pay_id"]])->value("payment_controller");
		$data["card_id"] = $mission["mission_cid"];
		$user_merchant = Db::name("payment_user")->where(["user_uid"=>$data["uid"],"user_pay_id"=>$data["pay_id"]])->value("user_merchant");
		$bindId = Db::name("payment_card")->where(["card_uid"=>$data["uid"],"card_pay_id"=>$data["pay_id"],"card_cid"=>$data["card_id"]])->value("card_pay_cid");
		$data["user_merchant"]=$user_merchant;
		$data["bindId"]=$bindId;
		$data["plan_pay_time"]=$plan["plan_pay_time"];
		$data["status"]=0;
		$data["fail_time"]=time();
		//halt($data);
		Db::name("repayment_fail_log")->insert($data);
	}
}